<template>
  <div class="article-list">
    <van-pull-refresh
      v-model="isLoading"
      @refresh="onRefresh"
      :success-text="refreshSuccessFinished"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <ArticleItem
          v-for="(item,index) in list"
          :key="index"
          :article="item"
        ></ArticleItem>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticles } from '@/api/article'
import ArticleItem from '@/components/article-item'
export default {
  name: 'ArticleList',
  components: {
    ArticleItem
  },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [],
      loading: false,
      finished: false,
      preTime: null,
      error: false,
      isLoading: false,
      refreshSuccessFinished: ''
    }
  },
  computed: {},
  watch: {},
  created () { },
  mounted () { },
  methods: {
    async onLoad () {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.preTime || Date.now(),
          with_top: 1
        })
        // 模拟异常
        // if (Math.random() > 0.5) {
        //   JSON.parse('skdfhsjk')
        // }
        console.log(data)
        const { results } = data.data
        this.list.push(...results)
        console.log(this.list)
        // 加载状态结束
        this.loading = false
        // // 数据全部加载完成
        if (results.length) {
          this.preTime = data.data.pre_timestamp
        } else {
          this.finished = true
        }
      } catch (err) {
        console.log(err)
        this.loading = false // 关闭 loading 效果
        this.error = true // 开启错误提示
      }
    },
    async onRefresh () {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 1
        })
        // 模拟异常
        // if (Math.random() > 0.5) {
        //   JSON.parse('skdfhsjk')
        // }
        console.log(data)
        const { results } = data.data
        this.list.unshift(...results)
        this.isLoading = false
        this.refreshSuccessFinished = `更新成功，新增${results.length}数据`
      } catch (err) {
        this.isLoading = false
        this.refreshSuccessFinished = '更新失败'
      }
    }
  }
}

</script>

<style scoped lang="less">
.article-list {
  height: 79vh;
  overflow-y: auto;
}
</style>
